package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.exception.StatisticsException;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 根据指定区间查询营业额
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        if(begin.isAfter(end)){
            throw new StatisticsException(MessageConstant.DATETIME_ERROR);
        }
        //所有日期可以自己计算处理
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){
            //将begin一直移动到和end一样
            begin = begin.plusDays(1);//包含最后一天了
            //每次添加
            dateList.add(begin);
        }
        //将每天的日期查询得到对应的营业额统计
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //查询当天的营业额 营业额是已完成的订单
            //获取当天的开始和结束时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);//日期加时间等于datetime
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //select sum(amount) from orders where status = 5 and order_time >= begin and order_time <= end
            Map map = new HashMap<>();
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            //如果为空的时候也会赋值 最后拼接字符串是null 不需要这个 自己赋值0.0
            turnover = turnover == null ? 0.0:turnover;
            turnoverList.add(turnover);
        }
        //最后转化成字符串封装vo
        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    /**
     * 根据指定区间查询用户
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //获取每天的日期
        if(begin.isAfter(end)){
            throw new StatisticsException(MessageConstant.DATETIME_ERROR);
        }
        //所有日期可以自己计算处理
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){
            //将begin一直移动到和end一样
            begin = begin.plusDays(1);//包含最后一天了
            //每次添加
            dateList.add(begin);
        }
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();

        for (LocalDate date : dateList) {
            //一天的开始时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            //一天的结束时间
            LocalDateTime endTime = LocalDateTime.of(date,LocalTime.MAX);
            Map map = new HashMap<>();
            map.put("end",endTime);
            //获取每天以前的老用户 select count(*) from user where create_time <= endTime
            Integer totalUser = userMapper.countByMap(map);
            //totalUser = totalUser == null ? 0 : totalUser;
            totalUserList.add(totalUser);
            //获取每天的新用户 select count(*) from user where create_time >= beginTime and create_time <= endTime
            map.put("begin",beginTime);
            Integer newUser = userMapper.countByMap(map);
            //newUser = newUser == null ? 0 : newUser;
            newUserList.add(newUser);
        }
        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }

    /**
     * 根据指定时间查询订单数据
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //每天的时间
        if(begin.isAfter(end)){
            throw new StatisticsException(MessageConstant.DATETIME_ERROR);
        }
        //所有日期可以自己计算处理
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){
            //将begin一直移动到和end一样
            begin = begin.plusDays(1);//包含最后一天了
            //每次添加
            dateList.add(begin);
        }
        List<Integer> orderCountList = new ArrayList<>();//每天的的订单集合
        List<Integer> validOrderCountList = new ArrayList<>();//每天的有效订单集合
        Integer totalOrderCount = 0;//总的订单数
        Integer validOrderCount = 0;//总的有效订单数
        Double orderCompletionRate;//有效订单率
        for (LocalDate date : dateList) {
            //一天的开始时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            //一天的结束时间
            LocalDateTime endTime = LocalDateTime.of(date,LocalTime.MAX);
            //查询当天的所有订单 select count(*) from orders where order_time <= and order_time >=
            Integer orderCount = getOrderCount(beginTime, endTime,null);
            //总的订单数
            totalOrderCount += orderCount;
            orderCountList.add(orderCount);
            //查询当天的已完成的有效订单 select count(*) from orders where order_time <= and order_time >= and status = 5
            Integer validCount = getOrderCount(beginTime, endTime,Orders.COMPLETED);
            //总的有效订单数
            validOrderCount += validCount;
            validOrderCountList.add(validCount);
        }
        //处理被除数为0的情况
        orderCompletionRate = totalOrderCount == 0 ? 0.0 : validOrderCount.doubleValue() / totalOrderCount;

        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 根据条件查询订单数量
     * @param beginTime
     * @param endTime
     * @param status
     * @return
     */
    private Integer getOrderCount(LocalDateTime beginTime, LocalDateTime endTime,Integer status) {
        Map map = new HashMap<>();
        map.put("begin", beginTime);
        map.put("end", endTime);
        map.put("status",status);
        return orderMapper.countByMap(map);
    }

    /**
     * 获取销量前十的商品
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        //根据时间查询符合时间的完成订单内连接查询出对应的订单明细表 的菜名和数量 降序查询
        LocalDateTime beginTime = LocalDateTime.of(begin,LocalTime.MIN);//最早的时间
        LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MAX);//最晚的时间
        List<GoodsSalesDTO>  list = orderMapper.getSalesTop10(beginTime,endTime);
        //封装成vo返回
        List<String> nameList = list.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = list.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        //1.获取要填充的营业额数据--最近30天的数据
        LocalDate beginDate = LocalDate.now().minusDays(30);//三十天的开始时间
        LocalDate endDate = LocalDate.now().minusDays(1);//昨天的最后时间
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(beginDate,LocalTime.MIN),LocalDateTime.of(endDate,LocalTime.MAX));

        //2.写入excel文件中
        //基于模板创建一个excel对象
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel  = new XSSFWorkbook(is);
            //获取sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充当前sheet页的数据
            sheet.getRow(1).getCell(1).setCellValue("时间："+beginDate+"至"+endDate);
            XSSFRow row = sheet.getRow(3);
            //填充当前第四行的单元格
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            //填充当前第五行的单元格
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            //填充每天的明细数据
            for (int i = 0; i < 30; i++) {
                //查询每天的营业额数据
                LocalDate date = beginDate.plusDays(i);
                BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                //填充到每一行
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessDataVO.getTurnover());
                row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            }
            //3.输出到客户端浏览器
            ServletOutputStream os = response.getOutputStream();
            excel.write(os);
            //4.关闭资源
            os.close();
            excel.close();
            is.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }



    }
}
